package com.ruizhong.centercontroll.server;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruizhong.centercontroll.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;

@ServerEndpoint(value = "/wsServer/{userId}", encoders = {ServerEncoder.class})
@Component
@Slf4j
public class WebSocketServer {
    private static int onlineCount = 0;
    public static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    private String userId = "";
    public static ConcurrentHashMap<String, Set<String>> pathMapClient = new ConcurrentHashMap<>();


    public Session getSession(){
        return session;
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入set中
        } else {
            webSocketMap.put(userId, this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());

        try {
            WSResult<String> stringWSResult = new WSResult<>();
            stringWSResult.setData("连接成功");
            sendMessage(stringWSResult);
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!");
        } catch (EncodeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
        pathMapClient.forEach(new BiConsumer<String, Set<String>>() {
            @Override
            public void accept(String s, Set<String> userids) {
                userids.remove(userId);
            }
        });
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (!"连接成功".equals(message)) {
            String[] msgSplit = message.split("#");
            String operation = msgSplit[0];

            if (operation.equals("connect")) {
                String pageName = msgSplit[1];
                String randomId = msgSplit[2];
                Set<String> webSocketServers = WebSocketServer.pathMapClient.get(pageName);
                if (CollectionUtils.isEmpty(webSocketServers)) {
                    webSocketServers = new HashSet<>();
                    WebSocketServer.pathMapClient.put(pageName, webSocketServers);
                }
                webSocketServers.add(randomId);
            }
            if (operation.equals("disconnect")){
                String pageName = msgSplit[1];
                String randomId = msgSplit[2];
                Set<String> webSocketServers = WebSocketServer.pathMapClient.get(pageName);
                if (CollectionUtils.isEmpty(webSocketServers)) {
                return;
                }
                webSocketServers.remove(randomId);
                TCPSender.closeTCPConnection(randomId);
            }
            if (operation.equals("mousePress")){
                String windowInfo = msgSplit[1];
                MouseInfo mouseInfo = new MouseInfo();
                mouseInfo.setFitWidth(Double.parseDouble(windowInfo.split("-")[2]));
                mouseInfo.setFitHeight(Double.parseDouble(windowInfo.split("-")[3]));
                mouseInfo.setX(Double.parseDouble(windowInfo.split("-")[0]));
                mouseInfo.setY(Double.parseDouble(windowInfo.split("-")[1]));
                RemoteControlUtil.Recalculate(mouseInfo);
                RemoteControlUtil.mousePress(mouseInfo);

            }
            if (operation.equals("mousePress")){
                String windowInfo = msgSplit[1];
                MouseInfo mouseInfo = new MouseInfo();
                mouseInfo.setFitWidth(Double.parseDouble(windowInfo.split("-")[2]));
                mouseInfo.setFitHeight(Double.parseDouble(windowInfo.split("-")[3]));
                mouseInfo.setX(Double.parseDouble(windowInfo.split("-")[0]));
                mouseInfo.setY(Double.parseDouble(windowInfo.split("-")[1]));
                RemoteControlUtil.Recalculate(mouseInfo);
                RemoteControlUtil.mouseRelease(mouseInfo);

            }

            if (operation.equals("clickRight")){

                RemoteControlUtil.clickRight();

            }
            if (operation.equals("inputKeyBoard")){
                try {
                    String value = msgSplit[1];
                    RemoteControlUtil.inputKeyBoard(value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (operation.equals("inputKeyBoardEnter")){
                RemoteControlUtil.inputKeyBoardEnter();
            }
            if (operation.equals("inputKeyBoardBackspace")){
                RemoteControlUtil.inputKeyBoardBackspace();
            }
        }

    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(WSResult message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(WSResult message, @PathParam("userId") String userId) throws IOException, EncodeException {
        log.info("发送消息到:" + userId + "，报文:" + message);
        if (!StringUtils.isEmpty(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线！");
        }
    }

    public static void broadcast(WSResult message) throws EncodeException, IOException {
        Enumeration<String> keys = webSocketMap.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            sendInfo(message, key);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
